package com.ld.explanation;

import com.intellij.openapi.editor.Editor;
import com.ld.utils.CommonUtils;

public class ENExplanation extends TextExplanation{

    public ENExplanation(Editor editor) {
        this.editor = editor;
    }

    @Override
    public String translation() {
        String selectedText = getSelectedText();
        String cache = translationCache.get(selectedText);
        if (cache != null){
            return cache;
        }
        String[] strings = selectedText.split("[\\u4E00-\\u9FA5]");
        for (String str:strings){
            int length = str.trim().length();
            if (length == 0){
                continue;
            }
            try {
                String participle = participle(str);
                String enToZh = enToZh(participle);
                if (CommonUtils.isMatch("[a-zA-Z]",enToZh) || enToZh.length() == 0){
                    continue;
                }
                selectedText = selectedText.replace(str,enToZh);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        translationCache.put(editor.getSelectionModel().getSelectedText(),selectedText);
        translationCache.put(selectedText,editor.getSelectionModel().getSelectedText());
        return selectedText;
    }
    private String participle(String v) {
        System.out.println("start->"+v);
        StringBuilder sb = new StringBuilder();
        String k ="";
        for(int i=0;i<v.length();i++) {
            char c = v.charAt(i);
            if(c == '.' || c== '-' || c=='_'){
                sb.append(" ");
            }else if(!Character.isLowerCase(c) && k.length() > 0) {//驼峰分词
                sb.append(" ");
                sb.append(c);
            }else{
                sb.append(c);
            }
            k= String.valueOf(c);
        }
        System.out.println("end->"+sb.toString());

        return sb.toString();

    }
}
